﻿#region MIT Licence
/*
 * Copyright (C) 2014 PdfCreative
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom 
 * the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included 
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;

using PdfCreative.Pdf.Writer;

namespace PdfCreative.Pdf.Graphics
{
    /// <summary>
    /// The RadialGradientBrush class represents a brush that fills with a radial gradient between two colours. The start and end points are
    /// ellipses and the space between is filled with concentric ellipses whose colour varies smoothly between the start and end colours.
    /// </summary>
    public class RadialGradientBrush : PatternBrush
    {
        // Private fields
        // ==============
        #region Private fields
        private Rectangle _bounds;
        private Colour _endColour;
        private float _exponent;
        private float _innerSize;
        private Colour _startColour;
        #endregion



        // Object overrides
        // ================
        #region Object overrides
        /// <summary>
        /// Indicates if this RadialGradientBrush is equal to a specified other instance.
        /// </summary>
        /// <param name="obj">The other instance to compare this RadialGradientBrush with</param>
        /// <returns>A boolean indicating that the two instances are equal (true) or not</returns>
        public override bool Equals(object obj)
        {
            RadialGradientBrush other = obj as RadialGradientBrush;
            return
                null != other &&
                other._bounds == _bounds &&
                other._endColour == _endColour &&
                other._exponent == _exponent &&
                other._innerSize == _innerSize &&
                other.StartColour == _startColour;
        }

        /// <summary>
        /// Retrieves the hash code for this RadialGradientBrush.
        /// </summary>
        /// <returns>The hash code.</returns>
        public override int GetHashCode()
        {
            int hashCode = _bounds.GetHashCode();
            hashCode ^= _endColour.GetHashCode();
            hashCode ^= _exponent.GetHashCode();
            hashCode ^= _innerSize.GetHashCode();
            hashCode ^= _startColour.GetHashCode();

            return hashCode;
        }
        #endregion



        // Brush overrides
        // ===============
        #region Brush overrides
        /// <summary>
        /// Writes the definition for the pattern resource used by this gradient brush.
        /// </summary>
        /// <param name="graphics">The graphics object to use as a context</param>
        /// <param name="writer">The writer to write to</param>
        /// <param name="resourceReference">The resource reference</param>
        /// <param name="scope">The scope if this instance of the resource.</param>
        public override void WriteResource(
            Graphics graphics, 
            PdfWriter writer, 
            PdfResourceReference resourceReference,
            ScopedResource scope)
        {
            // We create object references for the shading parameters and the shading function.
            PdfObjectReference pattern = resourceReference.ObjectReference;
            PdfObjectReference shading = writer.CreateObjectReference();
            PdfObjectReference function = writer.CreateObjectReference();

            // We open a pattern object. The pattern type is #2, for a shading pattern.
            writer.OpenObject(pattern, "Pattern");
            writer.WriteDictionaryEntry("PatternType", "2");
            writer.WriteDictionaryEntry("Shading", shading);

            // The pattern object of a radial gradient brush  has a matrix that transforms
            // the pattern coordinates to content coordinate space. We multiply the specified coordinate space matrix with this matrix
            // to arrive at a set of coordinates that applies to the gradient within its active coordinate space.
            Rectangle bounds = graphics.ConvertRectangle(_bounds);

            Matrix matrix = new Matrix(3,3, bounds.Width / 2, 0, bounds.Left, 0, bounds.Height / 2, scope.TargetBounds.Height - bounds.Bottom,0,0,1);
            Matrix transformedMatrix = scope.CoordinateSpace.Multiply(matrix);
            writer.WriteDictionaryEntry("Matrix", new float[]
              {
                  transformedMatrix[0,0],
                  transformedMatrix[0,1],
                  transformedMatrix[1,0],
                  transformedMatrix[1,1],
                  transformedMatrix[2,0],
                  transformedMatrix[2,1]
              });
            
            writer.CloseObject();

            // We write the shading object. This will have a type of #2, for a linear shading object, and refer
            // to a function object that interpolates the colours.
            writer.OpenObject(shading, "Shading");
            writer.WriteDictionaryEntry("ShadingType", 3);
            writer.WriteDictionaryEntry("ColorSpace", GetPdfColourSpace(_startColour));
            writer.WriteDictionaryEntry("Coords", new float[] { 1, 1, _innerSize, 1, 1, 1 });
            writer.WriteDictionaryEntry("Function", function);
            writer.WriteDictionaryEntry("Extend", "[true true]");
            writer.CloseObject();

            // We write the function object. This will have a type of #2, for a exponential interpolation function.
            writer.OpenObject(function);
            writer.WriteDictionaryEntry("FunctionType", "2");
            writer.WriteDictionaryEntry("Domain", "[0.0 1.0]");
            writer.WriteDictionaryEntry("C0", WriteColourArray(_startColour));
            writer.WriteDictionaryEntry("C1", WriteColourArray(_endColour));
            writer.WriteDictionaryEntry("N", _exponent);
            writer.CloseObject();


        } // WriteResource()

        /// <summary>
        /// Retrieves the scope that this brush is valid on.
        /// </summary>
        public override ResourceScope Scope
        {
            get { return ResourceScope.CurrentCoordinateSpace; }
        }
        #endregion



        // Public properties
        // =================
        #region Public properties
        /// <summary>
        /// Sets or retrieves the end colour for the gradient.
        /// </summary>
        public Colour EndColour
        {
            get { return _endColour; }
            set
            {
                if (null == value)
                    throw new ArgumentNullException("value");

                if (_startColour.ColourSpace != value.ColourSpace)
                    throw new ArgumentException("Start and end colour must use the same colour space");

                _endColour = value; 
            }
        }

        /// <summary>
        /// Sets or retrieves the exponent for the gradient. The default is 1.0, and this corresponds to a strictly linear progression.
        /// </summary>
        public float Exponent
        {
            get { return _exponent; }
            set
            {
                if (value < 0) throw new ArgumentOutOfRangeException("value", "The exponent must be at least 0. The default is 1.0");
                _exponent = value;
            }
        }

        /// <summary>
        /// Sets or retrieves the bounding box for the outer ellipse.
        /// </summary>
        public Rectangle Bounds
        {
            get { return _bounds; }
            set { _bounds = value; }
        }

        /// <summary>
        /// Sets or retrieves the size of the inner ellipse as a fraction of the size of the outer ellipse.
        /// This value must be between 0.0 and 1.0. The default value is 0.0.
        /// </summary>
        public float InnerSize
        {
            get { return _innerSize; }
            set{
                if (_innerSize < 0 || _innerSize > 1)
                    throw new ArgumentOutOfRangeException("value", "The InnerSize must be a value between 0.0 and 1.0");

                _innerSize = value; 
            }
        }

        /// <summary>
        /// Sets or retrieves the start colour for the brush.
        /// </summary>
        public Colour StartColour
        {
            get { return _startColour; }
            set
            {
                if (null == value)
                    throw new ArgumentNullException("value");

                if (_endColour.ColourSpace != value.ColourSpace)
                    throw new ArgumentException("Start and end colour must use the same colour space");

                _startColour = value; 
            }
        }
        #endregion



        // Public constructor
        // ==================
        #region Public constructor
        /// <summary>
        /// Constructs a new RadialGradientBrush instance using the specified colours and start- and end points.
        /// </summary>
        /// <param name="startColour">The start colour</param>
        /// <param name="endColour">The end colour</param>
        /// <param name="bounds">The bounding box of the outer ellipse.</param>
        public RadialGradientBrush(Colour startColour, Colour endColour, Rectangle bounds)
            : this(startColour, endColour, bounds, 0.25f, 1.0f) { }

        /// <summary>
        /// Constructs a new RadialGradientBrush instance using the specified colours and start- and end points.
        /// </summary>
        /// <param name="startColour">The start colour</param>
        /// <param name="endColour">The end colour</param>
        /// <param name="bounds">The bounding box of the outer ellipse.</param>
        /// <param name="innerSize">The size of the inner ellipse as a fraction of the size of the outer ellipse.
        /// This value must be between 0.0 and 1.0. The default value is 0.0.</param>
        /// <param name="exponent">The interpolation exponent (set to 1 for a linear interpolation between the start and end colours)</param>
        public RadialGradientBrush(Colour startColour, Colour endColour, Rectangle bounds, float innerSize, float exponent)
        {
            if (null == endColour)
                throw new ArgumentNullException("endColour");

            if (null == startColour)
                throw new ArgumentNullException("startColour");

            if (startColour.ColourSpace != endColour.ColourSpace)
                throw new ArgumentException("Start and end colour must use the same colour space");

            _endColour = endColour;
            _exponent = exponent;
            _bounds = bounds;
            _innerSize = innerSize;
            _startColour = startColour;
        }
        #endregion

    } // RadialGradientBrush
}
